# 导入
from DrissionPage import ChromiumPage
import pyautogui
import time
import os


def inandenter(filename):
    pyautogui.typewrite(filename, interval=0.1)  #输入文件路径
    time.sleep(2)
    pyautogui.press('enter')  #回车


def inandenter2(filename, i, page):
    try:
        pyautogui.typewrite(filename, interval=0.1)  #输入文件路径
        time.sleep(2)
        pyautogui.press('enter')  #回车
    except Exception as e:
        pyautogui.quit()
        pyautogui.quit()
        print(f"输入文件转换地址有误: {e}" + filename + f"第{i}次尝试")
        return pdf_exccel2(filename, ++i)


def pdf_exccel(url):
    try:
        download = 'D:\\liushuipdf\\yspdftoexcel'
        url = url.replace("D:/liushuipdf/", "D:\\liushuipdf\\")
        # 创建对象
        page = ChromiumPage()
        # 访问网页
        page.set.download_path(download)  #下载路径
        page.get('https://www.cleverpdf.com/cn/pdf-to-excel')  #访问页面
        page('#excel_sheet_worksheet').click()  # 选中"将整个 PDF 转换到一个工作表"# 选中"通过表格线识别表格"
        page('#excel_table_detection_border').click()  # 选中"通过表格线识别表格"
        page('#openPdf').click()  #点击上传
        time.sleep(2)
        inandenter(url)  # 弹框输入文件名
        page.wait.load_start(60)  #等待加载
        page('#choosefile_title').click()  #点击开始转换
        page.wait.load_start(180)  #等待加载
        time.sleep(10)
        page('#fileDownload').click()  #点击下载
        page.wait.download_begin()  # 等待下载开始
        page.wait.all_downloads_done()  #等待下载结束
        page.quit()  #关闭浏览器

        files = os.listdir(download)
        files.sort(key=lambda x: os.path.getmtime(os.path.join(download, x)), reverse=True)
        latest_file = files[0]
        print(latest_file)
        return download + '\\' + latest_file
    except Exception as e:
        print(f"pdf转excel发生错误: {e}")
        return ""


def pdf_exccel2(url, i):
    try:
        if i > 3:
            return "转化超时间"
        download = 'D:\\liushuipdf\\yspdftoexcel'
        url = url.replace("D:/liushuipdf/", "D:\\liushuipdf\\")
        # 创建对象
        page = ChromiumPage()
        # 访问网页
        page.set.download_path(download)  #下载路径
        page.get('https://tools.pdf24.org/zh/pdf-to-excel')  #访问页面
        page('.chooseFile').click()  #点击上传
        time.sleep(2)
        inandenter(url)  # 弹框输入文件名
        page.wait.load_start(20)  #等待加载
        page('#actionButtons').click()  #点击开始转换
        time.sleep(90)
        page.wait.load_start(30)  #等待加载
        page('#downloadTool').click()  #点击下载
        page.wait.download_begin()  # 等待下载开始
        page.wait.all_downloads_done()  #等待下载结束
        page.quit()  #关闭浏览器
        #获取下载最新的文件
        files = os.listdir(download)
        files.sort(key=lambda x: os.path.getmtime(os.path.join(download, x)), reverse=True)
        latest_file = files[0]
        print(latest_file)
        return download + '\\' + latest_file
    except Exception as e:
        page.quit()
        print(f"pdf转excel发生错误: {e}")
        return ""
    finally:
        page.quit()
